//
//  CBLightViewController.m
//  CROSBY
//
//  Created by 王华磊 on 2017/10/3.
//  Copyright © 2017年 Haley. All rights reserved.
//

#import "CBLightViewController.h"
#import "LSGraffitiViewController.h"
#import "BluetoothManager.h"

#import "LSCustomView.h"
#import "LSPatternButton.h"
#import "GrafftiCell.h"

#import "NSString+QCExtension.h"
#import "UIImageView+ATGetColor.h"
#import "ProgressHUD.h"

@interface CBLightViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>

@property (weak, nonatomic) IBOutlet UIView *topView;
@property (nonatomic, strong) UIView  *bottomLine;
@property (nonatomic, strong) NSMutableArray  *topButtons;

@property (strong, nonatomic) UISwitch          *switchView;

@property (strong, nonatomic) NSMutableArray  *patternBtns;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (strong, nonatomic) UITextView            *textView;

@property (strong, nonatomic) IBOutlet UIView   *bottomView;

@property (strong, nonatomic) IBOutlet UISlider *slider;
@property (weak, nonatomic) IBOutlet UISlider *speedSlider;
@property (weak, nonatomic) IBOutlet UILabel *modeLabel;
@property (weak, nonatomic) IBOutlet UIButton *leftBtn;
@property (weak, nonatomic) IBOutlet UIButton *rightBtn;

@property (strong, nonatomic) UIButton            *sendBtn;
@property (strong, nonatomic) UIButton            *addGraffBtn;

@property (strong, nonatomic) UITableView         *tableView;
@property (strong, nonatomic) NSArray             *graffData;

@property (strong, nonatomic) NSArray  *modes;

@end

@implementation CBLightViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setupLanguage];
    
    [self initNavigationBar];
    
    [self initTopView];
    
    [self initBottomView];
    
    [self initScrollView];
    
    [self loadGraffData];
    
    BOOL flag = [[NSUserDefaults standardUserDefaults] boolForKey:kShowedFirstLanguage];
    if (!flag) {
        [self showChoseLanguageView];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kShowedFirstLanguage];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChangeText:) name:UITextViewTextDidChangeNotification object:self.textView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - private method
- (void)setupLanguage
{
    self.navigationItem.title = showText(@"灯光");
    
    NSArray *topBtnTitles = @[showText(@"图案"),showText(@"文字"),showText(@"涂鸦")];
    for (int i = 0; i < topBtnTitles.count; i++) {
        NSString *title = topBtnTitles[i];
        UIButton *button;
        if (self.topButtons.count == topBtnTitles.count) {
            button = self.topButtons[i];
            [button setTitle:title forState:UIControlStateNormal];
        }
    }
    
    [self.sendBtn setTitle:showText(@"发送") forState:UIControlStateNormal];
    
    [self.addGraffBtn setTitle:showText(@"添加涂鸦") forState:UIControlStateNormal];
    
    NSString *mode = self.modeLabel.text;
    
    NSInteger index = [self.modes indexOfObject:mode];
    
    self.modes = @[showText(@"静态"),showText(@"向左"),showText(@"向右"),showText(@"向上"),showText(@"向下"),showText(@"雪花"),showText(@"画卷"),showText(@"镭射")];
    
    self.modeLabel.text = self.modes[index];
}

- (void)initNavigationBar
{
    UISwitch *openSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 60, 40)];
    openSwitch.on = YES;
    [openSwitch addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];
    self.switchView = openSwitch;
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:openSwitch];
    self.navigationItem.leftBarButtonItem = leftItem;
}

- (void)initTopView
{
    self.topView.frame = CGRectMake(0, 0, kWidth, 44);
    
    [self.topView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.topButtons removeAllObjects];
    
    UIImageView *topBgView = [[UIImageView alloc] initWithFrame:_topView.bounds];
//    topBgView.image = [UIImage imageNamed:@"mote_tab_bg"];
//    topBgView.contentMode = UIViewContentModeScaleToFill;
    topBgView.backgroundColor = [UIColor colorWithHexString:kThemeColor];
    [self.topView addSubview:topBgView];
    
    NSArray *topBtnTitles = @[showText(@"图案"),showText(@"文字"),showText(@"涂鸦")];
    self.topButtons = [[NSMutableArray alloc] initWithCapacity:topBtnTitles.count];
    
    CGFloat btnW = kWidth/topBtnTitles.count;
    CGFloat btnH = 44;
    for (int i = 0; i < topBtnTitles.count; i++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(btnW*i, 0, btnW, btnH)];
        button.tag = i;
        if (i == 0) {
            button.selected = YES;
        }
        [button setTitle:topBtnTitles[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor yellowColor] forState:UIControlStateSelected];
        button.titleLabel.font = [UIFont systemFontOfSize:15.0f];
        [button addTarget:self action:@selector(typeClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.topView addSubview:button];
        [self.topButtons addObject:button];
    }
    
    self.bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0, 42, btnW, 2)];
    self.bottomLine.backgroundColor = [UIColor yellowColor];
    [self.topView addSubview:self.bottomLine];
}

- (void)initScrollView
{    
    CGFloat srollViewH = kHeight-64-49-44-112-kTopSafeHeight-kBottomSafeHeight;
    self.scrollView.frame = CGRectMake(0, 44, kWidth, srollViewH);
    self.scrollView.backgroundColor = [UIColor clearColor];
    self.scrollView.contentSize = CGSizeMake(kWidth, srollViewH);
    self.scrollView.pagingEnabled = YES;
    self.scrollView.scrollEnabled = NO;
    
    // 第一页
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kWidth, srollViewH)];;
    [self.scrollView addSubview:scrollView];

    CGFloat contentH = 5;
    self.patternBtns = [[NSMutableArray alloc] initWithCapacity:16];
    for (int i = 0; i < 18; i++) {
        NSString *imageName = nil;
        if (i == 0) {
            imageName = @"CR";
        } else if (i == 1) {
            imageName = @"CROSBY";
        } else {
            imageName = [NSString stringWithFormat:@"ic_drawable_%d",i - 1];
        }
        UIImage *image = [UIImage imageNamed:imageName];
        CGFloat height = (kWidth-6) * image.size.height / image.size.width + 10;
        LSPatternButton *button = [[LSPatternButton alloc] initWithFrame:CGRectMake(0, 5 + (height + 5) * i, kWidth, height)];
        button.patternImage = image;
        button.tag = i;
        [button addTarget:self action:@selector(patternChose:) forControlEvents:UIControlEventTouchUpInside];
        contentH += (height + 5);
        [scrollView addSubview:button];
        [self.patternBtns addObject:button];
    }
    
    scrollView.contentSize = CGSizeMake(kWidth, contentH);
    // 第二页
    UIView *secondView = [[UIView alloc] initWithFrame:CGRectMake(kWidth, 0, kWidth, srollViewH)];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBg)];
    [secondView addGestureRecognizer:tapGesture];
    
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 10, kWidth - 40, srollViewH-20 - 100)];
    textView.keyboardType = UIKeyboardTypeEmailAddress;
    textView.returnKeyType = UIReturnKeyDone;
    textView.delegate = self;
    textView.font = [UIFont systemFontOfSize:20.f];
    [secondView addSubview:textView];
    self.textView = textView;
    
    UIButton *sendBtn = [[UIButton alloc] initWithFrame:CGRectMake((kWidth-120)*0.5, srollViewH-50, 120, 40)];
    sendBtn.backgroundColor = [UIColor colorWithHexString:kThemeColor];
    [sendBtn setTitle:showText(@"发送") forState:UIControlStateNormal];
    [sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(sendClick:) forControlEvents:UIControlEventTouchUpInside];
    [secondView addSubview:sendBtn];
    self.sendBtn = sendBtn;
    
    [self.scrollView addSubview:secondView];
    
    // 第三页
    UIView *thirdView = [[UIView alloc] initWithFrame:CGRectMake(kWidth * 2, 0, kWidth, srollViewH)];
    UIButton *addBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, kWidth-20, 40)];
    [addBtn setTitle:showText(@"添加涂鸦") forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addClick:) forControlEvents:UIControlEventTouchUpInside];
    addBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    addBtn.layer.borderWidth = 1;
    [thirdView addSubview:addBtn];
    self.addGraffBtn = addBtn;
    
    CGFloat tableViewH = srollViewH - 60;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 60, kWidth, tableViewH) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    CGFloat graH = kWidth / kGraffiCols * kGraffiRows;
    self.tableView.rowHeight = graH + 10;
    [thirdView addSubview:self.tableView];
    
    [self.scrollView addSubview:thirdView];
    
    self.scrollView.contentSize = CGSizeMake(kWidth * 3, srollViewH);
}

- (void)initBottomView
{
    self.modes = @[showText(@"静态"),showText(@"向左"),showText(@"向右"),showText(@"向上"),showText(@"向下"),showText(@"雪花"),showText(@"画卷"),showText(@"镭射")];
    
    self.bottomView.frame = CGRectMake(0, kHeight-64-kTopSafeHeight-kBottomSafeHeight-49-112, kWidth, 112);
    self.bottomView.backgroundColor = [UIColor clearColor];
    
    [self.leftBtn setImage:[UIImage imageNamed:@"ic_chose_pra"] forState:UIControlStateNormal];
    self.leftBtn.frame = CGRectMake(8, 8, 30, 30);
    [self.leftBtn addTarget:self action:@selector(leftClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.modeLabel.text = [self.modes firstObject];
    self.modeLabel.frame = CGRectMake((kWidth-120)*0.5, 8, 120, 30);
    
    self.rightBtn.frame = CGRectMake(kWidth-30-8, 8, 30, 30);
    [self.rightBtn setImage:[UIImage imageNamed:@"ic_chose_next"] forState:UIControlStateNormal];
    [self.rightBtn addTarget:self action:@selector(rightClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.slider.frame = CGRectMake(8, 41, kWidth - 16, 30);
    self.slider.minimumValueImage = [UIImage imageNamed:@"brightness_left_new"];
    self.slider.maximumValueImage = [UIImage imageNamed:@"brightness_right_new"];
    [self.slider setThumbImage:[UIImage imageNamed:@"ic_thumb"] forState:UIControlStateNormal];
    [self.slider addTarget:self action:@selector(sliderChange:) forControlEvents:UIControlEventValueChanged];
    
    self.speedSlider.frame = CGRectMake(8, 80, kWidth - 16, 30);
    self.speedSlider.minimumValueImage = [UIImage imageNamed:@"speed_decrease"];
    self.speedSlider.maximumValueImage = [UIImage imageNamed:@"speed_increase"];
    [self.speedSlider setThumbImage:[UIImage imageNamed:@"ic_thumb"] forState:UIControlStateNormal];
    [self.speedSlider addTarget:self action:@selector(speedSliderChange:) forControlEvents:UIControlEventValueChanged];
}

- (void)loadGraffData
{
    NSArray *graffDataList = [[NSUserDefaults standardUserDefaults] objectForKey:kGraffDataListKey];
    self.graffData = graffDataList;
    [self.tableView reloadData];
}

#pragma mark - btn events
// 顶部图案、文字、涂鸦类型选择
- (void)typeClick:(UIButton *)btn
{
    NSInteger index = btn.tag;
    for (UIButton *btn in self.topButtons) {
        btn.selected = NO;
    }
    
    CGFloat btnW = kWidth/self.topButtons.count;
    btn.selected = YES;
    self.bottomLine.frame = CGRectMake(btnW*index, 42, btnW, 2);
    
    if (index != 1) {
        [self tapBg];
    }
    
    [self.scrollView setContentOffset:CGPointMake(index*kWidth, 0) animated:YES];
}

- (void)addClick:(UIButton *)btn
{
    NSLog(@"添加涂鸦");
    LSGraffitiViewController *graffVC = [[LSGraffitiViewController alloc] init];
    graffVC.hidesBottomBarWhenPushed = YES;
    graffVC.graffCompletion = ^{
        [self loadGraffData];
    };
    [self.navigationController pushViewController:graffVC animated:YES];
}

- (void)tapBg
{
    [self.view endEditing:YES];
}

- (void)valueChange:(UISwitch *)openSwitch
{
    BOOL on = openSwitch.on;
    
    NSString *dataString = [NSString stringWithFormat:@"000209%02x",on];
    NSString *finalString = [NSString finalDataWith:dataString];
    
    [[BluetoothManager standardManager] writCommad:finalString];
}

- (void)patternChose:(UIButton *)btn
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kMusicShouldStopNotification object:nil];
    
    for (LSPatternButton *button in self.patternBtns) {
        button.layer.borderColor = [UIColor clearColor].CGColor;
        button.layer.borderWidth = 0.0;
        button.selected = NO;
    }
    
    btn.layer.borderWidth = 2.0;
    btn.layer.borderColor = [UIColor redColor].CGColor;
    btn.selected = YES;
    
    int index = (int)btn.tag;
    if (index == 0) {
        NSString *dataString = @"0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x88,0x88,0x80,0xA0,0xB0,0xE8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00";
        NSArray *array = [dataString componentsSeparatedByString:@","];
        int length = (int)array.count + 1;
        NSString *hexString = [NSString stringWithFormat:@"%04x03",length];
        for (NSString *string in array) {
            NSString *data = [string stringByReplacingOccurrencesOfString:@"0x" withString:@""];
            hexString = [hexString stringByAppendingString:data];
        }
        NSLog(@"value:%@",hexString);
        NSString *finalString = [NSString finalDataWith:hexString];
        [[BluetoothManager standardManager] writCommad:finalString];
    } else if (index == 1) {
        NSString *dataString = @"0x00,0x70,0x88,0x88,0x88,0x00,0x00,0xF8,0xA0,0xB0,0x48,0x00,0x70,0x88,0x88,0x88,0x70,0x00,0x00,0x48,0xA8,0xA8,0x90,0x00,0x00,0xF8,0xA8,0xA8,0x50,0x00,0x80,0x40,0x38,0x40,0x80,0x00";
        NSArray *array = [dataString componentsSeparatedByString:@","];
        int length = (int)array.count + 1;
        NSString *hexString = [NSString stringWithFormat:@"%04x03",length];
        for (NSString *string in array) {
            NSString *data = [string stringByReplacingOccurrencesOfString:@"0x" withString:@""];
            hexString = [hexString stringByAppendingString:data];
        }
        NSLog(@"value:%@",hexString);
        NSString *finalString = [NSString finalDataWith:hexString];
        [[BluetoothManager standardManager] writCommad:finalString];
    } else {
        NSString *lengthString = @"0002";
        NSString *dataString = [NSString stringWithFormat:@"%@05%@",lengthString,[NSString ToHex:index-1]];
        NSLog(@"选中固定图案的按钮:%@",dataString);
        NSString *commdString = [NSString finalDataWith:dataString];
        [[BluetoothManager standardManager] writCommad:commdString];
    }
}

- (void)sendClick:(UIButton *)btn
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kMusicShouldStopNotification object:nil];
    
    [self.view endEditing:YES];
    NSString *text = self.textView.text;
    if (text.length == 0) {
        [ProgressHUD showError:showText(@"请输入内容")];
        return;
    }
    
    if ((text.length >= 32)) {
        [ProgressHUD showError:showText(@"不能大于32个字符")];
        return;
    }
    
    if ([NSString hasChinese:text]) {
        [ProgressHUD showError:showText(@"暂不支持中文")];
        return;
    }
    
    int length = (int)text.length + 1;
    NSString *sendText = [NSString stringWithFormat:@"%04x02",length];
    for (int i = 0 ;i < text.length; i++) {
        int asciiCode = [text characterAtIndex:i];
//        if (0x4E00 <= asciiCode  && asciiCode <= 0x9FA5) {
//            NSRange range = NSMakeRange(i, 1);
//            NSString *ch = [text substringWithRange:range];
//
//        }
        NSString *hexStr = [NSString stringWithFormat:@"%02x",asciiCode];
        sendText = [sendText stringByAppendingString:hexStr];
    }
    NSString *finalString = [NSString finalDataWith:sendText];
    
    NSString *firstText = @"00010a";
    NSString *firstcmd = [NSString finalDataWith:firstText];
    [[BluetoothManager standardManager] writCommad:firstcmd];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
        [[BluetoothManager standardManager] writCommad:finalString];
    });
}

// 左移按钮
- (void)leftClick:(UIButton *)btn
{
    NSString *currentMode = self.modeLabel.text;
    NSInteger index = [self.modes indexOfObject:currentMode];
    NSInteger previousIndex = 0;
    previousIndex = index - 1;
    if (previousIndex < 0) {
        previousIndex = self.modes.count - 1;
    }
    self.modeLabel.text = [self.modes objectAtIndex:previousIndex];
    
    int type = (int)previousIndex+1;
    
    NSString *lengthString = @"0002";
    NSString *dataString = [NSString stringWithFormat:@"%@06%@",lengthString,[NSString ToHex:type]];
    
    NSString *commond = [NSString finalDataWith:dataString];
    [[BluetoothManager standardManager] writCommad:commond];
}

// 右移按钮
- (void)rightClick:(UIButton *)btn
{
    NSString *currentMode = self.modeLabel.text;
    NSInteger index = [self.modes indexOfObject:currentMode];
    NSInteger nextIndex = 0;
    nextIndex = index + 1;
    if (nextIndex >= self.modes.count) {
        nextIndex = 0;
    }
    self.modeLabel.text = [self.modes objectAtIndex:nextIndex];
    
    int type = (int)nextIndex+1;
    
    NSString *lengthString = @"0002";
    NSString *dataString = [NSString stringWithFormat:@"%@06%@",lengthString,[NSString ToHex:type]];
    
    NSString *commond = [NSString finalDataWith:dataString];
    [[BluetoothManager standardManager] writCommad:commond];
}

// 速度slider拖动事件
- (void)speedSliderChange:(UISlider *)slider
{
    int speed = (int)slider.value;
    
    NSString *lengthString = @"0002";
    NSString *dataString = [NSString stringWithFormat:@"%@07%@",lengthString,[NSString ToHex:speed]];
    
    NSString *commond = [NSString finalDataWith:dataString];
    [[BluetoothManager standardManager] writCommad:commond];
}

// 亮度slider拖动事件
- (void)sliderChange:(UISlider *)slider
{
    int brightness = (int)slider.value;
    
    NSString *lengthString = @"0002";
    NSString *dataString = [NSString stringWithFormat:@"%@08%@",lengthString,[NSString ToHex:brightness]];
    
    NSString *commond = [NSString finalDataWith:dataString];
    [[BluetoothManager standardManager] writCommad:commond];
}

#pragma mark - notification method
- (void)textViewDidChangeText:(NSNotification *)notification
{
    static int kMaxLength = 32;
    UITextView *textView = (UITextView *)notification.object;
    NSString *toBeString = textView.text;
    // 获取键盘输入模式
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage];
    // 中文输入的时候,可能有markedText(高亮选择的文字),需要判断这种状态
    // zh-Hans表示简体中文输入, 包括简体拼音，健体五笔，简体手写
    if ([lang isEqualToString:@"zh-Hans"]) {
        textView.text = @"";
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:showText(@"暂不支持中文") preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:showText(@"好") style:UIAlertActionStyleCancel handler:nil];
        [alertVC addAction:cancelAction];
        [self presentViewController:alertVC animated:YES completion:nil];
//        UITextRange *selectedRange = [textView markedTextRange];
//        //获取高亮选择部分
//        UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
//        // 没有高亮选择的字，表明输入结束,则对已输入的文字进行字数统计和限制
//        if (!position) {
//            if (toBeString.length > kMaxLength) {
//                // 截取子串
//                textView.text = [toBeString substringToIndex:kMaxLength];
//            }
//        } else { // 有高亮选择的字符串，则暂不对文字进行统计和限制
//            NSLog(@"11111111111111========      %@",position);
//        }
    } else {
        // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
        if (toBeString.length > kMaxLength) {
            // 截取子串
            textView.text = [toBeString substringToIndex:kMaxLength];
        }
    }
}

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        [self.textView resignFirstResponder];
        return NO;
    }
    
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.graffData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GrafftiCell *cell = [GrafftiCell cellWithTableView:tableView];
    cell.data = self.graffData[indexPath.row];
    
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return showText(@"删除");
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *data = [NSMutableArray arrayWithArray:self.graffData];
    int index = (int)indexPath.row;
    [data removeObjectAtIndex:index];
    
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:kGraffDataListKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self loadGraffData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *data = self.graffData[indexPath.row];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kMusicShouldStopNotification object:nil];
    
    int length = (int)data.count + 1;
    NSString *hexString = [NSString stringWithFormat:@"%04x03",length];
    for (int i = 0; i < data.count; i++) {
        NSArray *cols = data[i];
        int sum = 0;
        for (int j = 0; j < cols.count; j++) {
            NSNumber *number = cols[j];
            sum += [number intValue] * (int)pow(2, 7-j);
        }
        
        NSString *colSum = [NSString stringWithFormat:@"%02x",sum];
        hexString = [hexString stringByAppendingString:colSum];
    }
    NSLog(@"value:%@",hexString);
    NSString *finalString = [NSString finalDataWith:hexString];
    
    NSString *firstText = @"00010a";
    NSString *firstcmd = [NSString finalDataWith:firstText];
    [[BluetoothManager standardManager] writCommad:firstcmd];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
        [[BluetoothManager standardManager] writCommad:finalString];
    });
}

@end
